<?php
namespace app\index\controller;
use app\BaseController;
use think\Request;
use think\facade\View;
use app\index\model;
use think\facade\Session;
class Index extends BaseController
{

    //后台首页
    public function index()
    {
        return View::fetch();
    }

    //文章管理
    public function article(Request $request)
    {
            $article = new model\Article;
            //栏目
            if($request->param('category_id')){
                $arrId = implode(',',Model\Category::where('p_id',$request->param('category_id'))->column('id'));
                $article = $article->where('category_id','in',$arrId.','.$request->param('category_id'));
            }
            //时间排序
            if($order = $request->param('order')){
                if($order == 'show-desc'){
                    $article = $article->order('save','desc');
                }else{
                    if($order == 'time-asc'){
                        $article = $article->order('create_time','asc');
                    }else{
                        $article = $article->order('create_time','desc');
                    }
                }
            }
            //关键字
            if($request->param('keywords')){
                $article = $article->whereLike('title',$request->param('keywords').'%');
            }
            View::assign([
                'order' =>$request->param('order'),//排序
                'category_id'=>$request->param('category_id'),//栏目
                'keywords' => $request->param('keywords'), //关键字
                'list'=>$article->paginate(3,false,['query'=>$this->request->param()]),
                //展示栏目
                'data'=>model\Category::getTree(model\Category::select()->toArray()),
                ]);
        return View::fetch();
    }

    //回收站显示的文章
    public function recycle()
    {
        View::assign('list',model\Article::where('stauts',0)->paginate(2));
        return View::fetch();
    }

    //回收站文章还原
    public function restore(Request $request)
    {
        $res = new model\Article;
        $res->update([
            'stauts'=>1,
        ],['id'=>$request->post('id')]);
        if($res){
            $this->success('文章还原成功');
        }else{
            $this->error('文章还原失败');
        }
    }

    //图像处理
    public function upload(){
        $file = request()->file('thumb');
        $image = \think\Image::open($file);
        $path = './upload/'.date('Ymd').'/'.session_create_id().'.'.$image->type();
        if(!file_exists('./upload/'.date('Ymd'))){
           mkdir('./upload/'.date('Ymd'),0777,true);
        }
        // 给原图左上角添加水印并保存water_image.png
        $image->thumb(200,200)->text('刀客软件学院',
            getcwd().'/static/fonts/STKAITI.TTF',25,'#cc3f86',1)
            ->save($path);
            return  '/'.$path;
    }
    //发布文章
    public function cp_article_edit(Request $request)
    {   //便利栏目
        $info =  model\Category::select()->toArray();
        View::assign('list',model\Category::getTree($info));

        if($request->isAjax()){
            //接收
            $data = $request->post();
            //验证
            $valiCms = new \app\index\validate\Cms;
            if(!$valiCms->check($data)){
                $this->error($valiCms->getError());
            }
            $data['content'] = strip_tags($data['content']);//过滤p标签
            $result = model\Article::create([
                'user_id'=>1,
                'category_id'=>$data['category_id'],
                'title'=>$data['title'],
                'description'=> $data['description'] ?? strip_tags(mb_substr($data['content'],0,30)),
                'thumb'=>$data['thumb'],
                'stauts'=>1,
                'save'=>$data['save'],
                'is_newest'=>0,
            ]);
           $ArticleDetail = model\ArticleDetail::create([
                'article_id'=>$result->id,
                'content'=>strip_tags($data['content']) //过滤p标签
            ]);
            model\Keyword::create([
                'article_id'=>$result->id,
                'keywords'=>$data['keywords'],
            ]);
           if($ArticleDetail->id){
               $this->success('文章发布成功');
           }else{
               $this->error('文章发布失败');
           }
       }

        return View::fetch();
    }

    //文章编辑
    public function cp_article_edit_2(Request $request)
    {
        //便利栏目
        $info =  model\Category::select()->toArray();
        View::assign('list',model\Category::getTree($info));
        //把修改的文章发送到前端展示
        View::assign('data',model\Article::select()->where('id',$request->get('id')));
        //更改要修改的数据
        if($request->isAjax()){
            //接收
            $data = $request->post();
            if(empty($data)) $this->error('');//无效操作
            if(empty($data['description'])) $data['description'] = strip_tags(mb_substr($data['content'],0,30));
            //验证
            $valiCms = new \app\index\validate\Cms;
            if(!$valiCms->check($data)){
                $this->error($valiCms->getError());
            }
            $data['content'] = strip_tags($data['content']);//过滤p标签
            $article = model\Article::find($data['id']);
            $article->save($data);
            $article->keyword();
            $article->articleDetail();
            if($article){
                $this->success('文章修改成功');
            }else{
                $this->error('文章修改失败');
            }
        }
        return View::fetch();
    }

    //设置文章最新
    public function newest(Request $request)
    {
        $res = new model\Article;
        $res->update([
            'is_newest'=>1,
        ],['id'=>$_POST['id']]);
        if($res){
            $this->success('设置热门成功');
        }else{
            $this->error('设置失败');
        }

    }

    //设置文章取消最新
    public function onnew()
    {
        $res = new model\Article;
        $res->update([
            'is_newest'=>0,
        ],['id'=>$_POST['id']]);
        if($res){
            $this->success('设置热门成功');
        }else{
            $this->error('设置失败');
        }
    }

    //软删除文章
    public function article_del(Request $request)
    {
        $article = new model\Article;
       //管理员可以 对所有帖子进行删除
        if(Session::get('userinfo')['status'] == 1){
            $article->update([
               'stauts'=>0,
            ],['id' => $request->get('id')]);
            if($article){
                $this->success('帖子删除成功');
            }else{
                $this->error('帖子删除失败');
            }
        }else{
            //普通用户：判断删除的帖子,是不是自己的
            if(Session::get('userinfo')['id'] !== model\Article::where('id',$_GET['id'])->find()['user_id']){
                $this->error('不能删除他人的帖子');
            }else{
                $article->update([
                    'stauts'=>0,
                ],['id' => $request->get('id')]);
                if($article){
                    $this->success('帖子删除成功');
                }else{
                    $this->error('帖子删除失败');
                }
            }
        }
    }

    //后台首页(显示服务器信息)
    public function cp_index()
    {
        return View::fetch();
    }

    //个人中心
    public function my_center()
    {
        View::assign('user',Session::get('userinfo'));
        return View::fetch();
    }

}
